import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { AlertController, ToastController } from 'ionic-angular';

import { AppVersion } from '@ionic-native/app-version';

import { UpgradeAppProvider } from "../upgrade-app/upgrade-app";

/*
  Generated class for the ApiProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/

@Injectable()
export class ApiProvider {

  public IPProt = 'http://39.104.122.0:8286';//'http://192.168.0.169:8085';//'http://192.168.0.28:8080';//'http://192.168.0.169:8088';//'http://192.168.0.169:8088';//'http://192.168.0.28:8080';
  public filePath = "http://edu.hyzylab.com";//'http://192.168.0.169:8019';//'http://192.168.0.28:8080';//'http://192.168.0.169:8019';//'http://192.168.0.169:8019';//'http://192.168.0.28:8180'//'http://edu.hyzylab.com'
  //发送消息（不是发服务器）
  public sendwsinfo='ws://edu.hyzylab.com';//"ws://192.168.0.169:8019";
  //接收弹幕消息
  public receivews='ws://39.104.122.0:8481';//"ws://192.168.0.169:8088";
  //接收服务器消息
  public receiveserve='ws://39.104.122.0:8286';//"ws://192.168.0.169:8085";



  // public IPProt = 'http://192.168.0.35:8081';//'http://192.168.0.28:8080';//'http://192.168.0.169:8088';//'http://192.168.0.169:8088';//'http://192.168.0.28:8080';
  // public filePath = "http://192.168.0.35:8081";//'http://192.168.0.169:8019';//'http://192.168.0.28:8080';//'http://192.168.0.169:8019';//'http://192.168.0.169:8019';//'http://192.168.0.28:8180'//'http://edu.hyzylab.com'
  // //发送消息（不是发服务器）
  // public sendwsinfo='ws://192.168.0.35:8081';//"ws://192.168.0.169:8019";
  // //接收弹幕消息
  // public receivews='ws://192.168.0.35:8081';//"ws://192.168.0.169:8088";
  // //接收服务器消息
  // public receiveserve='ws://192.168.0.35:8081';//"ws://192.168.0.169:8085";





  public API = '/FourInOneTeacherAppServer';
  public url = this.IPProt + this.API;

  public MobileAPI = '/FourInOneTeacherMobile';
  public mobileUrl = this.IPProt + this.MobileAPI;


  constructor(public http: HttpClient, private alertCtrl: AlertController, private toastCtrl: ToastController, private upgradeApi: UpgradeAppProvider, public appVersion: AppVersion) {
    //console.log('Hello ApiProvider Provider');
  }

  // 通用的范型

  // _post<I,O>(url,parmas): Promise<O>{
  //   return new Promise((resolve, reject)=>{
  //     this.http.post(url,parmas).subscribe( res => {
  //       resolve(<O>res);
  //     })
  //   })
  // }

  /**
   * 提交请求
   * @param url action地址
   * @param parmas 参数
   * @returns {Observable<Object>}
   */
  post(url, parmas) {
    //const options =
    // this.createAuthorizationHeader(headers);
    return this.http.post(this.url + url, JSON.stringify(parmas));
  }
  post2(url, parmas) {
    //const options =
    // this.createAuthorizationHeader(headers);
    return this.http.post(url, JSON.stringify(parmas));
  }

  post1(url, parmas) {
    //const options =
    // this.createAuthorizationHeader(headers);
    return new Promise((resolve, reject) => {
      this.http.post(this.url + url, JSON.stringify(parmas)).subscribe(res => {
        resolve(res);
      }, error => {
        throw error;
        //reject(error);

        //this.showToast(error,'bottom');
      })
    })
  }

  get(url) {
    return this.http.get(this.url + url);
  }

  /**
   * 错误提示
   * @param msg 消息内容
   */
  errorAlert(msg) {
    let alert = this.alertCtrl.create({
      title: '警告',
      message: msg,
      buttons: ['确定']
    });
    alert.present();
  }

  /**
   * 在相应位置显示toast
   * @param msg
   * @param position
   */
  showToast(msg, position) {
    let toast = this.toastCtrl.create({
      message: msg,
      duration: 3000,
      position: position
    });

    toast.onDidDismiss(() => {
      console.log('Dismissed toast');
    });

    toast.present();
  }

  /**
   * 检查版本更新
   */
  checkVersion(page) {
    let versionCode;
    this.appVersion.getVersionNumber().then(val => {
      versionCode = val;
    });

    this.post("/version/getVersionByType.do", { type: 2 }).subscribe(item => {
      if (item["Code"] == "11111111") {
        this.showToast(item["Message"], "bottom");
      }
      else {
        if (item["version"].version_code == versionCode && page != "main") {
          this.showToast("当前版本已是最新版本!", "bottom");
        }
        else if (item["version"].version_code != versionCode) {
          let confirm = this.alertCtrl.create({
            title: '发现新版本',
            subTitle: item["version"].version_name,
            message: item["version"].repair_content,
            buttons: [
              {
                text: '取消',
                handler: () => {
                }
              },
              {
                text: '立即升级',
                handler: () => {
                  //console.log(item["version"].path);

                  this.upgradeApi.downloadApp(item["version"].path);
                }
              }
            ]
          });
          confirm.present();
        }
      }
    });
  }

  /**
   * 人脸识别
   */
  searchFace(data) {
    return this.post('/sign/searchFace.do', data);
  }

  /**
   * 人脸识别注册
   */
  faceSign(data) {
    return this.post('/sign/registerFace.do', data);
  }

  /**
   * 检测人脸是否注册
   */
  checkFace(data) {
    return this.post('/sign/checkFace.do ', data);
  }

  /**
   * 识别成功后调用签到
   */
  signBeforeFace(data) {
    return this.post('/sign/signByMachineCode', data);
  }
  /**
   * 识别成功后调用签到
   */
  signAfterFaceUnit(data) {
    return this.post('/sign/signByUnit', data);
  }
}
